package com.sinogrand.elevator.ui.screens

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material.icons.filled.Business
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.platform.LocalContext
import com.sinogrand.elevator.data.models.ApprovalRecordItem
import com.sinogrand.elevator.data.models.ProjectItem as ApiProjectItem
import com.sinogrand.elevator.ui.components.ProjectItem as UiProjectItem
import com.sinogrand.elevator.ui.components.ProjectItemCard
import com.sinogrand.elevator.ui.components.ProjectStatus
import com.sinogrand.elevator.repository.ProjectRepository
import com.sinogrand.elevator.utils.Constants
import com.sinogrand.elevator.utils.PaginationUtils
import com.sinogrand.elevator.network.NetworkClient
import com.sinogrand.elevator.utils.LogTags
import com.google.gson.JsonObject
import kotlinx.coroutines.launch
import kotlinx.coroutines.delay
import android.util.Log
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import kotlin.random.Random

// 用户数据模型
data class User(
    val id: String,
    val name: String,
    val department: String,
    val phone: String,
    val avatar: String? = null
)

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MyWorkOrderScreen(
    onNavigateBack: () -> Unit,
    onNavigateToWorkOrder: (Int) -> Unit = {}
) {
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    
    // Tab状态管理
    var selectedTab by rememberSaveable { mutableStateOf(0) }
    val tabs = listOf("安装工单", "维保工单")
    
    // 状态管理
    var projectList by remember { mutableStateOf<List<UiProjectItem>>(emptyList()) }
    var isLoading by remember { mutableStateOf(false) }
    var isRefreshing by remember { mutableStateOf(false) }
    var isLoadingMore by remember { mutableStateOf(false) }
    var errorMessage by remember { mutableStateOf<String?>(null) }
    var currentPage by remember { mutableStateOf(1) }
    var canLoadMore by remember { mutableStateOf(true) }
    var searchQuery by remember { mutableStateOf("") }
    var isSearching by remember { mutableStateOf(false) }
    
    // 认领状态管理
    var claimingProjectId by remember { mutableStateOf<String?>(null) }
    var claimedProjectIds by remember { mutableStateOf<Set<String>>(emptySet()) }
    
    // Snackbar状态管理
    var snackbarHostState by remember { mutableStateOf(SnackbarHostState()) }
    
    // 底部弹窗状态管理
    var showAssignBottomSheet by remember { mutableStateOf(false) }
    var currentAssignProjectId by remember { mutableStateOf<String?>(null) }
    var selectedUserId by remember { mutableStateOf<String?>(null) }
    var isAssigning by remember { mutableStateOf(false) }
    val bottomSheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
    
    val listState = rememberLazyListState()
    
    // Repository
    val projectRepository = remember { ProjectRepository(context) }
    
    // 模拟用户列表
    val mockUsers = remember {
        listOf(
            User("1", "张三", "技术部", "13800138001"),
            User("2", "李四", "工程部", "13800138002"),
            User("3", "王五", "技术部", "13800138003"),
            User("4", "赵六", "工程部", "13800138004"),
            User("5", "钱七", "技术部", "13800138005"),
            User("6", "孙八", "工程部", "13800138006"),
            User("7", "周九", "技术部", "13800138007"),
            User("8", "吴十", "工程部", "13800138008"),
            User("9", "郑十一", "技术部", "13800138009"),
            User("10", "王十二", "工程部", "13800138010"),
            User("11", "李十三", "技术部", "13800138011"),
            User("12", "张十四", "工程部", "13800138012"),
            User("13", "刘十五", "技术部", "13800138013"),
            User("14", "陈十六", "工程部", "13800138014"),
            User("15", "杨十七", "技术部", "13800138015")
        )
    }
    
    // 生成随机计划时间（YYYY-MM-DD格式）
    fun generateRandomPlannedDate(): String {
        val startDate = LocalDate.now()
        val randomDays = Random.nextLong(0, 90) // 未来90天内
        val randomDate = startDate.plusDays(randomDays)
        return randomDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
    }
    
    // 转换项目状态
    fun convertProjectStatus(status: Int): ProjectStatus {
        return when (status) {
            Constants.ProjectStatus.CONTRACT_PENDING -> ProjectStatus.PENDING
            Constants.ProjectStatus.DISABLED -> ProjectStatus.PENDING
            Constants.ProjectStatus.PROCESSING -> ProjectStatus.IN_PROGRESS
            Constants.ProjectStatus.ARCHIVE_PENDING -> ProjectStatus.APPROVED
            Constants.ProjectStatus.ARCHIVED -> ProjectStatus.COMPLETED
            Constants.ProjectStatus.MAINTENANCE -> ProjectStatus.MAINTENANCE
            else -> ProjectStatus.PENDING
        }
    }
    
    // 转换 API 项目数据为 UI 项目数据
    fun convertApiProjectToUi(apiProject: ApiProjectItem): UiProjectItem {
        val plannedDate = generateRandomPlannedDate()
        val planType = if (selectedTab == 0) "安装计划" else "维保计划"
        val status = if (selectedTab == 0) convertProjectStatus(apiProject.status) else ProjectStatus.MAINTENANCE
        
        return UiProjectItem(
            id = apiProject.id.toString(),
            name = apiProject.name,
            description = "$planType：$plannedDate | ${apiProject.address} | 电梯数量: ${apiProject.elevator_count}",
            status = status,
            imageUrl = null
        )
    }
    
    // 加载数据函数
    suspend fun loadProjectData(page: Int = 1, isRefresh: Boolean = false, searchName: String? = null) {
        try {
            Log.d(LogTags.MAIN_ACTIVITY, "开始加载项目数据，页码: $page, Tab: ${tabs[selectedTab]}, 搜索: $searchName")
            
            if (isRefresh) {
                isRefreshing = true
            } else if (page == 1) {
                isLoading = true
            } else {
                isLoadingMore = true
            }
            
            errorMessage = null
            
            val result = projectRepository.getInstallProjectList(
                name = searchName,
                page = page,
                size = 20
            )
            
            result.fold(
                onSuccess = { response ->
                    val uiProjects = response.list.map { convertApiProjectToUi(it) }
                    
                    if (page == 1) {
                        projectList = uiProjects
                    } else {
                        projectList = projectList + uiProjects
                    }
                    
                    // 使用分页工具判断是否还有下一页
                    canLoadMore = PaginationUtils.hasNextPage(response.page_info)
                    currentPage = page
                    
                    Log.i(LogTags.MAIN_ACTIVITY, "✅ 成功加载项目数据: ${projectList.size}条")
                },
                onFailure = { error ->
                    Log.e(LogTags.MAIN_ACTIVITY, "❌ 加载项目数据失败: ${error.message}")
                    errorMessage = error.message
                }
            )
        } catch (e: Exception) {
            Log.e(LogTags.MAIN_ACTIVITY, "💥 加载项目数据异常: ${e.message}", e)
            errorMessage = "加载失败: ${e.message}"
        } finally {
            isLoading = false
            isRefreshing = false
            isLoadingMore = false
        }
    }
    
    // 下拉刷新
    fun onRefresh() {
        scope.launch {
            loadProjectData(isRefresh = true, searchName = if (searchQuery.isNotEmpty()) searchQuery else null)
        }
    }
    
    // 加载更多
    fun loadMore() {
        if (!isLoadingMore && canLoadMore) {
            scope.launch {
                loadProjectData(currentPage + 1, searchName = if (searchQuery.isNotEmpty()) searchQuery else null)
            }
        }
    }
    
    // 搜索功能
    fun handleSearch(query: String) {
        searchQuery = query
        isSearching = true
        
        scope.launch {
            delay(300) // 防抖延迟
            loadProjectData(searchName = if (query.isNotEmpty()) query else null)
            isSearching = false
        }
    }
    
    // Tab切换
    fun onTabChanged(tabIndex: Int) {
        selectedTab = tabIndex
        // 不需要手动调用loadProjectData，LaunchedEffect会自动处理
    }
    
    // 清除搜索
    fun handleClearSearch() {
        searchQuery = ""
        handleSearch("")
    }
    
    // 认领项目函数
    suspend fun claimProject(projectId: String) {
        try {
            Log.d(LogTags.MAIN_ACTIVITY, "开始认领项目: $projectId")
            claimingProjectId = projectId
            
            // 模拟网络请求延迟2秒
            delay(2000)
            
            // 模拟认领成功
            claimedProjectIds = claimedProjectIds + projectId
            claimingProjectId = null
            
            // 显示成功提示
            snackbarHostState.showSnackbar(
                message = "认领成功！",
                duration = SnackbarDuration.Short
            )
            
            Log.i(LogTags.MAIN_ACTIVITY, "✅ 项目认领成功: $projectId")
        } catch (e: Exception) {
            Log.e(LogTags.MAIN_ACTIVITY, "❌ 项目认领失败: ${e.message}", e)
            claimingProjectId = null
            
            // 显示失败提示
            snackbarHostState.showSnackbar(
                message = "认领失败，请重试",
                duration = SnackbarDuration.Short
            )
        }
    }
    
    // 分配项目函数
    suspend fun assignProject(projectId: String, userId: String) {
        try {
            Log.d(LogTags.MAIN_ACTIVITY, "开始分配项目: $projectId 给用户: $userId")
            isAssigning = true
            
            // 模拟网络请求延迟2秒
            delay(2000)
            
            // 模拟分配成功
            isAssigning = false
            showAssignBottomSheet = false
            selectedUserId = null
            currentAssignProjectId = null
            
            // 显示成功提示
            snackbarHostState.showSnackbar(
                message = "分配成功！",
                duration = SnackbarDuration.Short
            )
            
            Log.i(LogTags.MAIN_ACTIVITY, "✅ 项目分配成功: $projectId -> $userId")
        } catch (e: Exception) {
            Log.e(LogTags.MAIN_ACTIVITY, "❌ 项目分配失败: ${e.message}", e)
            isAssigning = false
            
            // 显示失败提示
            snackbarHostState.showSnackbar(
                message = "分配失败，请重试",
                duration = SnackbarDuration.Short
            )
        }
    }
    
    // 打开分配弹窗
    fun openAssignBottomSheet(projectId: String) {
        currentAssignProjectId = projectId
        selectedUserId = null
        showAssignBottomSheet = true
    }
    
    // 初始加载和Tab切换时重新加载
    LaunchedEffect(selectedTab) {
        loadProjectData(searchName = if (searchQuery.isNotEmpty()) searchQuery else null)
    }
    
    // 控制底部弹窗显示
    LaunchedEffect(showAssignBottomSheet) {
        if (showAssignBottomSheet) {
            bottomSheetState.show()
        } else {
            bottomSheetState.hide()
        }
    }
    
    if (showAssignBottomSheet) {
        ModalBottomSheet(
            onDismissRequest = {
                showAssignBottomSheet = false
                selectedUserId = null
                currentAssignProjectId = null
            },
            sheetState = bottomSheetState
        ) {
            AssignUserBottomSheet(
                users = mockUsers,
                selectedUserId = selectedUserId,
                onUserSelected = { userId -> selectedUserId = userId },
                onAssign = {
                    currentAssignProjectId?.let { projectId ->
                        scope.launch {
                            assignProject(projectId, selectedUserId!!)
                        }
                    }
                },
                onDismiss = {
                    showAssignBottomSheet = false
                    selectedUserId = null
                    currentAssignProjectId = null
                },
                isAssigning = isAssigning
            )
        }
    }
    
    Scaffold(
            topBar = {
                TopAppBar(
                    title = {
                        Text(
                            text = "我的工单",
                            fontSize = 18.sp,
                            fontWeight = FontWeight.Bold,
                            color = Color(0xFF1F2937)
                        )
                    },
                    navigationIcon = {
                        IconButton(onClick = onNavigateBack) {
                            Icon(
                                imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                                contentDescription = "返回"
                            )
                        }
                    },
                    colors = TopAppBarDefaults.topAppBarColors(
                        containerColor = Color.White,
                        titleContentColor = Color(0xFF1F2937),
                        navigationIconContentColor = Color(0xFF1F2937)
                    ),
                    modifier = Modifier.shadow(2.dp)
                )
            },
            snackbarHost = {
                SnackbarHost(
                    hostState = snackbarHostState,
                    snackbar = { snackbarData ->
                        Snackbar(
                            snackbarData = snackbarData,
                            containerColor = Color(0xFF10B981),
                            contentColor = Color.White,
                            shape = RoundedCornerShape(8.dp)
                        )
                    }
                )
            }
        ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(
                    Brush.verticalGradient(
                        colors = listOf(
                            Color(0xFFF8FAFC),
                            Color(0xFFF1F5F9)
                        )
                    )
                )
                .padding(paddingValues)
        ) {
            // Tab选择器
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(start = 16.dp, top = 16.dp, end = 16.dp, bottom = 8.dp),
                colors = CardDefaults.cardColors(
                    containerColor = Color.White
                ),
                elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
                shape = RoundedCornerShape(12.dp)
            ) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(4.dp),
                    horizontalArrangement = Arrangement.SpaceEvenly
                ) {
                    tabs.forEachIndexed { index, tabTitle ->
                        WorkOrderTabButton(
                            text = tabTitle,
                            isSelected = selectedTab == index,
                            onClick = { onTabChanged(index) },
                            modifier = Modifier.weight(1f)
                        )
                    }
                }
            }
            
            // 搜索框
            WorkOrderSearchBar(
                query = searchQuery,
                onQueryChange = { searchQuery = it },
                onSearch = { handleSearch(searchQuery) },
                onClear = { handleClearSearch() },
                placeholder = "搜索工单...",
                isSearching = isSearching,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp)
                    .height(48.dp)
            )
            
            // 列表内容
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f)
            ) {
                when {
                    isLoading && projectList.isEmpty() -> {
                        // 初始加载状态
                        Box(
                            modifier = Modifier.fillMaxSize(),
                            contentAlignment = Alignment.Center
                        ) {
                            Column(
                                horizontalAlignment = Alignment.CenterHorizontally
                            ) {
                                CircularProgressIndicator(
                                    color = Color(0xFF3B82F6)
                                )
                                Spacer(modifier = Modifier.height(16.dp))
                                Text(
                                    text = "加载中...",
                                    fontSize = 16.sp,
                                    color = Color(0xFF6B7280)
                                )
                            }
                        }
                    }
                    
                    errorMessage != null && projectList.isEmpty() -> {
                        // 错误状态
                        Box(
                            modifier = Modifier.fillMaxSize(),
                            contentAlignment = Alignment.Center
                        ) {
                            Column(
                                horizontalAlignment = Alignment.CenterHorizontally
                            ) {
                                Text(
                                    text = "加载失败",
                                    fontSize = 18.sp,
                                    fontWeight = FontWeight.Medium,
                                    color = Color(0xFFDC2626)
                                )
                                Spacer(modifier = Modifier.height(8.dp))
                                Text(
                                    text = errorMessage ?: "未知错误",
                                    fontSize = 14.sp,
                                    color = Color(0xFF6B7280)
                                )
                                Spacer(modifier = Modifier.height(16.dp))
                                Button(
                                    onClick = {
                                        errorMessage = null
                                        scope.launch {
                                            loadProjectData(searchName = if (searchQuery.isNotEmpty()) searchQuery else null)
                                        }
                                    }
                                ) {
                                    Text("重试")
                                }
                            }
                        }
                    }
                    
                    projectList.isEmpty() -> {
                        // 空状态
                        Box(
                            modifier = Modifier.fillMaxSize(),
                            contentAlignment = Alignment.Center
                        ) {
                            Column(
                                horizontalAlignment = Alignment.CenterHorizontally
                            ) {
                                Text(
                                    text = "暂无${tabs[selectedTab]}记录",
                                    fontSize = 18.sp,
                                    fontWeight = FontWeight.Medium,
                                    color = Color(0xFF6B7280)
                                )
                                Spacer(modifier = Modifier.height(8.dp))
                                Text(
                                    text = "您还没有任何${tabs[selectedTab]}的项目记录",
                                    fontSize = 14.sp,
                                    color = Color(0xFF9CA3AF)
                                )
                            }
                        }
                    }
                    
                    else -> {
                        // 列表内容
                        LazyColumn(
                            state = listState,
                            modifier = Modifier.fillMaxSize(),
                            contentPadding = PaddingValues(16.dp),
                            verticalArrangement = Arrangement.spacedBy(12.dp)
                        ) {
                            items(
                                count = projectList.size,
                                key = { index -> projectList[index].id }
                            ) { index ->
                                val project = projectList[index]
                                WorkOrderProjectItemCard(
                                    project = project,
                                    isClaiming = claimingProjectId == project.id,
                                    isClaimed = claimedProjectIds.contains(project.id),
                                    isClaimDisabled = claimingProjectId != null && claimingProjectId != project.id,
                                    onAssignClick = {
                                        Log.d(LogTags.MAIN_ACTIVITY, "分配项目: ${project.id}")
                                        openAssignBottomSheet(project.id)
                                    },
                                    onClaimClick = {
                                        Log.d(LogTags.MAIN_ACTIVITY, "认领项目: ${project.id}")
                                        scope.launch {
                                            claimProject(project.id)
                                        }
                                    },
                                    onClick = {
                                        Log.d(LogTags.MAIN_ACTIVITY, "点击项目: ${project.id}")
                                        onNavigateToWorkOrder(project.id.toInt())
                                    }
                                )
                            }
                            
                            // 加载更多指示器
                            if (isLoadingMore && projectList.isNotEmpty()) {
                                item {
                                    Box(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(16.dp),
                                        contentAlignment = Alignment.Center
                                    ) {
                                        CircularProgressIndicator(
                                            modifier = Modifier.size(24.dp),
                                            color = Color(0xFF3B82F6)
                                        )
                                    }
                                }
                            }
                            
                            // 没有更多数据提示
                            if (!canLoadMore && projectList.isNotEmpty()) {
                                item {
                                    Box(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(16.dp),
                                        contentAlignment = Alignment.Center
                                    ) {
                                        Text(
                                            text = "没有更多数据了",
                                            fontSize = 14.sp,
                                            color = Color(0xFF9CA3AF)
                                        )
                                    }
                                }
                            }
                        }
                    }
                }
                
                // 下拉刷新指示器
                if (isRefreshing) {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(top = 16.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(24.dp),
                            color = Color(0xFF3B82F6)
                        )
                    }
                }
            }
        }
    }
}

@Composable
fun WorkOrderSearchBar(
    query: String,
    onQueryChange: (String) -> Unit,
    onSearch: () -> Unit,
    onClear: () -> Unit = {},
    placeholder: String = "搜索",
    isSearching: Boolean = false,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = Color.White
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
        shape = RoundedCornerShape(12.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 10.dp, vertical = 8.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                imageVector = Icons.Default.Search,
                contentDescription = null,
                tint = Color(0xFF6B7280),
                modifier = Modifier.size(24.dp)
            )
            
            Spacer(modifier = Modifier.width(6.dp))
            
            val keyboardController = LocalSoftwareKeyboardController.current
            
            BasicTextField(
                value = query,
                onValueChange = onQueryChange,
                modifier = Modifier
                    .weight(1f)
                    .height(48.dp),
                textStyle = TextStyle(
                    fontSize = 14.sp,
                    color = Color(0xFF1F2937)
                ),
                decorationBox = { innerTextField ->
                    Box(
                        modifier = Modifier.fillMaxWidth(),
                        contentAlignment = Alignment.CenterStart
                    ) {
                        if (query.isEmpty()) {
                            Text(
                                text = placeholder,
                                color = Color(0xFF9CA3AF),
                                fontSize = 14.sp,
                                lineHeight = 10.sp
                            )
                        }
                        innerTextField()
                    }
                },
                singleLine = true,
                keyboardOptions = KeyboardOptions(
                    imeAction = ImeAction.Search
                ),
                keyboardActions = KeyboardActions(
                    onSearch = {
                        onSearch()
                        keyboardController?.hide()
                    }
                )
            )
            
            if (isSearching) {
                Box(
                    modifier = Modifier.size(28.dp),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(16.dp),
                        strokeWidth = 2.dp,
                        color = Color(0xFF3B82F6)
                    )
                }
            } else if (query.isNotEmpty()) {
                IconButton(
                    onClick = onClear,
                    modifier = Modifier.size(28.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.Clear,
                        contentDescription = "清除搜索",
                        tint = Color(0xFF6B7280),
                        modifier = Modifier.size(14.dp)
                    )
                }
            }
        }
    }
}

@Composable
fun WorkOrderTabButton(
    text: String,
    isSelected: Boolean,
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    if (isSelected) {
        Card(
            modifier = modifier
                .padding(2.dp)
                .clip(RoundedCornerShape(8.dp)),
            colors = CardDefaults.cardColors(
                containerColor = Color(0xFF3B82F6)
            ),
            elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
        ) {
            TextButton(
                onClick = onClick,
                modifier = Modifier.fillMaxWidth()
            ) {
                Text(
                    text = text,
                    color = Color.White,
                    fontSize = 14.sp,
                    fontWeight = FontWeight.Bold
                )
            }
        }
    } else {
        TextButton(
            onClick = onClick,
            modifier = modifier.fillMaxWidth()
        ) {
            Text(
                text = text,
                color = Color(0xFF6B7280),
                fontSize = 14.sp,
                fontWeight = FontWeight.Medium
            )
        }
    }
}

@Composable
fun WorkOrderRecordListItem(
    workOrder: ApprovalRecordItem,
    onClick: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .clickable { onClick() },
        colors = CardDefaults.cardColors(
            containerColor = Color.White
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        shape = RoundedCornerShape(12.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            // 标题
            Text(
                text = workOrder.title,
                fontSize = 16.sp,
                fontWeight = FontWeight.Medium,
                color = Color(0xFF1F2937),
                maxLines = 2,
                overflow = TextOverflow.Ellipsis
            )
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // 模板名称
            Text(
                text = workOrder.template_name,
                fontSize = 14.sp,
                color = Color(0xFF6B7280),
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
            
            Spacer(modifier = Modifier.height(4.dp))
            
            // 项目名称
            Text(
                text = workOrder.project_name,
                fontSize = 14.sp,
                color = Color(0xFF6B7280),
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
        }
    }
}

@Composable
fun WorkOrderProjectItemCard(
    project: UiProjectItem,
    modifier: Modifier = Modifier,
    isClaiming: Boolean = false,
    isClaimed: Boolean = false,
    isClaimDisabled: Boolean = false,
    onAssignClick: () -> Unit = {},
    onClaimClick: () -> Unit = {},
    onClick: () -> Unit = {}
) {
    Card(
        modifier = modifier
            .fillMaxWidth()
            .clickable { onClick() },
        colors = CardDefaults.cardColors(
            containerColor = Color.White
        ),
        elevation = CardDefaults.cardElevation(
            defaultElevation = 2.dp,
            pressedElevation = 4.dp
        ),
        shape = RoundedCornerShape(12.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 左侧图片
            Box(
                modifier = Modifier
                    .size(60.dp)
                    .clip(RoundedCornerShape(12.dp))
                    .background(Color(0xFFF3F4F6)),
                contentAlignment = Alignment.Center
            ) {
                Icon(
                    imageVector = Icons.Default.Business,
                    contentDescription = null,
                    modifier = Modifier.size(24.dp),
                    tint = Color(0xFF9CA3AF)
                )
            }
            
            Spacer(modifier = Modifier.width(12.dp))
            
            // 中间内容
            Column(
                modifier = Modifier.weight(1f)
            ) {
                Text(
                    text = project.name,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color(0xFF1F2937),
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
                
                Spacer(modifier = Modifier.height(4.dp))
                
                Text(
                    text = project.description,
                    fontSize = 14.sp,
                    color = Color(0xFF6B7280),
                    lineHeight = 18.sp
                )
            }
            
            // 右侧按钮组
            Spacer(modifier = Modifier.width(8.dp))
            
            Column(
                verticalArrangement = Arrangement.spacedBy(6.dp)
            ) {
                // 分配按钮
                Button(
                    onClick = onAssignClick,
                    modifier = Modifier
                        .width(80.dp)
                        .height(32.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color(0xFF3B82F6)
                    ),
                    shape = RoundedCornerShape(8.dp),
                    contentPadding = PaddingValues(horizontal = 4.dp, vertical = 0.dp)
                ) {
                    Text(
                        text = "分配",
                        fontSize = 12.sp,
                        fontWeight = FontWeight.Medium,
                        color = Color.White
                    )
                }
                
                // 认领按钮
                Button(
                    onClick = onClaimClick,
                    enabled = !isClaimDisabled && !isClaimed,
                    modifier = Modifier
                        .width(80.dp)
                        .height(32.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = if (isClaimed) Color(0xFF6B7280) else Color(0xFF10B981),
                        disabledContainerColor = Color(0xFFE5E7EB)
                    ),
                    shape = RoundedCornerShape(8.dp),
                    contentPadding = PaddingValues(horizontal = 4.dp, vertical = 0.dp)
                ) {
                    if (isClaiming) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(12.dp),
                            strokeWidth = 2.dp,
                            color = Color.White
                        )
                    } else {
                        Text(
                            text = if (isClaimed) "已认领" else "认领",
                            fontSize = 12.sp,
                            fontWeight = FontWeight.Medium,
                            color = if (isClaimDisabled) Color(0xFF9CA3AF) else Color.White
                        )
                    }
                }
            }
        }
    }
}

// 分配用户底部弹窗组件
@Composable
fun AssignUserBottomSheet(
    users: List<User>,
    selectedUserId: String?,
    onUserSelected: (String) -> Unit,
    onAssign: () -> Unit,
    onDismiss: () -> Unit,
    isAssigning: Boolean
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp)
    ) {
        // 标题栏
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = "选择分配用户",
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold,
                color = Color(0xFF1F2937)
            )
            
            IconButton(onClick = onDismiss) {
                Icon(
                    imageVector = Icons.Default.Clear,
                    contentDescription = "关闭",
                    tint = Color(0xFF6B7280)
                )
            }
        }
        
        Spacer(modifier = Modifier.height(16.dp))
        
        // 用户列表
        LazyColumn(
            modifier = Modifier
                .fillMaxWidth()
                .height(400.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            items(users.size) { index ->
                val user = users[index]
                UserItemCard(
                    user = user,
                    isSelected = selectedUserId == user.id,
                    isDisabled = isAssigning,
                    onClick = { 
                        if (!isAssigning) {
                            onUserSelected(user.id) 
                        }
                    }
                )
            }
        }
        
        Spacer(modifier = Modifier.height(16.dp))
        
        // 分配按钮
        Button(
            onClick = onAssign,
            enabled = selectedUserId != null && !isAssigning,
            modifier = Modifier
                .fillMaxWidth()
                .height(48.dp),
            colors = ButtonDefaults.buttonColors(
                containerColor = Color(0xFF3B82F6),
                disabledContainerColor = Color(0xFFE5E7EB)
            ),
            shape = RoundedCornerShape(8.dp)
        ) {
            if (isAssigning) {
                CircularProgressIndicator(
                    modifier = Modifier.size(20.dp),
                    strokeWidth = 2.dp,
                    color = Color.White
                )
            } else {
                Text(
                    text = "确认分配",
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Medium,
                    color = if (selectedUserId != null) Color.White else Color(0xFF9CA3AF)
                )
            }
        }
    }
}

// 用户卡片组件
@Composable
fun UserItemCard(
    user: User,
    isSelected: Boolean,
    isDisabled: Boolean = false,
    onClick: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(enabled = !isDisabled) { onClick() },
        colors = CardDefaults.cardColors(
            containerColor = when {
                isDisabled -> Color(0xFFF9FAFB)
                isSelected -> Color(0xFFEBF8FF)
                else -> Color.White
            }
        ),
        elevation = CardDefaults.cardElevation(
            defaultElevation = if (isSelected && !isDisabled) 4.dp else 2.dp
        ),
        shape = RoundedCornerShape(12.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 用户头像
            Box(
                modifier = Modifier
                    .size(48.dp)
                    .clip(RoundedCornerShape(24.dp))
                    .background(Color(0xFF3B82F6)),
                contentAlignment = Alignment.Center
            ) {
                Icon(
                    imageVector = Icons.Default.Person,
                    contentDescription = null,
                    modifier = Modifier.size(24.dp),
                    tint = Color.White
                )
            }
            
            Spacer(modifier = Modifier.width(12.dp))
            
            // 用户信息
            Column(
                modifier = Modifier.weight(1f)
            ) {
                Text(
                    text = user.name,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    color = if (isDisabled) Color(0xFF9CA3AF) else Color(0xFF1F2937)
                )
                
                Spacer(modifier = Modifier.height(4.dp))
                
                Text(
                    text = user.department,
                    fontSize = 14.sp,
                    color = if (isDisabled) Color(0xFFD1D5DB) else Color(0xFF6B7280)
                )
                
                Spacer(modifier = Modifier.height(2.dp))
                
                Text(
                    text = user.phone,
                    fontSize = 12.sp,
                    color = if (isDisabled) Color(0xFFE5E7EB) else Color(0xFF9CA3AF)
                )
            }
            
            // 选中状态
            if (isSelected) {
                Icon(
                    imageVector = Icons.Default.Check,
                    contentDescription = "已选中",
                    tint = if (isDisabled) Color(0xFF9CA3AF) else Color(0xFF3B82F6),
                    modifier = Modifier.size(24.dp)
                )
            }
        }
    }
}
